Tomáš Pospíšek's Notizblock

a non-intrusive, localized, C function wrapper debugging technique

I was debugging a C program and wanted to have a line with context printed each time a certain function would be called.

Replacing each occurence of "fun" with a "fun_debug" wrapper function would have been very invasive in that the diff would get polluted with all those replacements.

Also in case I'd submit my patches that would enable the program in question to be debugged more easily I doubt the original author would be happy to have all those calls be replaced by wrapper functions.

So my solution is to temporarily "alias" the problematic function with the help of a define:

#include <stdio.h>

int fun() {
  printf("fun\n");
}

int fun_orig() {
  return fun();
}

int fun_dbg() {
  printf("dbg\n");
  return fun();
}

#define fun fun_dbg

main() {
  fun();
}

// "undefine"
#define fun fun_orig

I wonder whether this is a known technique or whether it's too trivial for an average C coal mine worker to even mention...

Tomáš Pospíšek, 2015-02-25

Articles